import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Image, Text, Button, ScrollView} from '@tarojs/components';

import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import {
  OSS_PATH_PREFIX,
  RETURN_ANIMATION,
  OVER_ANIMATION,
  DEFALUT_OPERATES,
  OSS_BASE_PATH_PREFIX,
  CATCHING_OPERATES,
  CODE_SUCCESS,
  GAME_SHARE_TITLE,
  TASK_CONDITION_TYPE,
  SECONDS_FORMAT,
  NAVBAR_TITLE,
} from './constant';

import {BACKAGROUND_IMAGE_BASE64} from './imageBase64';
import moment from 'dayjs';

// 引入组件
import ResultModal from './components/ResultModal/ResultModal';
import TaskModal from './components/TaskModal/TaskModal';
import MemberModal from './components/MemberModal/MemberModal';
import NextItemModal from './components/NextItemModal/NextItemModal';
import WishModal from './components/WishModal/WishModal';
import StrategyModal from './components/StrategyModal/StrategyModal';
import PropModal from './components/PropModal/PropModal';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import {handleUrl, fetchModal, setModalShow} from 'wmkit';

import './index.less';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class CatchPlaythingPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值

  constructor(props) {
    super(props);
    this.state = {
      query: {}, // 路径中携带参数

      // 抓取状态
      catchingConfig: {
        start: false,
        type: '', // 那种类型的抓取切换不同的按钮
        ropeAnimationCount: 0, // 统计绳子动画个数，动画都是按步骤播放的
      },

      // 绳子配置
      ropeAnimation: {
        createAnimation: Taro.createAnimation({
          duration: 0,
          timingFunction: 'linear',
        }),
        animation: {actions: []},
        config: {
          duration: 1000,
          timingFunction: 'linear',
        },
      },

      // 球配置
      playthingAnimation: {
        createAnimation: Taro.createAnimation({
          duration: 0,
          timingFunction: 'linear',
        }),
        animation: {actions: []},
        config: {
          duration: 1000,
          timingFunction: 'linear',
        },
      },

      // 图片
      pics: {
        headerTitle: OSS_PATH_PREFIX + '/headerTitle.png', // 标题
        wish: OSS_PATH_PREFIX + '/Wish.png', // 许愿
        ChessPreview: OSS_BASE_PATH_PREFIX + '/nextIcon.png', // 下期预告
        outIcon: OSS_PATH_PREFIX + '/outIcon.png', // 出口
        topUp: OSS_PATH_PREFIX + '/topUp.png', // 充值图标
        coin: OSS_PATH_PREFIX + '/coin.png', /// 游戏币
        // music: OSS_PATH_PREFIX + '/music.png', // 音乐
        // share: OSS_PATH_PREFIX + '/share.png', // 分享
        catchSingleButton: OSS_PATH_PREFIX + '/catchingButton.png', // 单次抓取中
        catchMoreButton: OSS_PATH_PREFIX + '/catchingLargeRed.png', // 多次抓取中
        gift: OSS_BASE_PATH_PREFIX + '/giftIcon.png', // 领福利
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
        catchIcon: OSS_PATH_PREFIX + '/catchPic.png', // 抓取整体
        propBuffIcon: OSS_BASE_PATH_PREFIX + '/propBuffIcon.png', // 道具图标
      },

      // 操作页面,后台配置不同心愿的价格不同
      currentOperates: -1, // 点击哪个操作

      gameOperates: DEFALUT_OPERATES, // 游戏按钮配置
      wishOperates: [],

      // 模态框显示
      modal: {
        type: '', // 多个模态框
        visible: false,
        item: null,
      },

      // 气泡
      message: {
        title: '',
        visible: false,
      },

      selectedProp: null, // 选择道具

      // 广告
      adModal: {
        isModalFlag: false,
        imgUrl: '',
        jumpPage: {},
        nextPopupId: '',
        type: 'magicDollHome',
      },

      navbarSettings: {
        navBarHeight: 0, // 导航栏高度
        menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
        menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
        menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
      },
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.handleAdModalUpdateStatus(''); // 广告弹出
    this.props.actions.init();
  }

  componentDidMount(): void {
    this.getNavHeight();
  }

  /**
   * 获取navbar高度
   */
  getNavHeight() {
    var sysinfo = Taro.getSystemInfoSync();
    const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    let navBarHeight = sysinfo.statusBarHeight + 44;
    let menuRight = sysinfo.screenWidth - menuButtonInfo.right;
    let menuTop = menuButtonInfo.top;
    let menuHeight = menuButtonInfo.height;
    console.log('navBarHeight', navBarHeight, 'sysinfo', sysinfo);
    this.setState({
      navbarSettings: {
        ...this.state.navbarSettings,
        navBarHeight, // 导航栏高度
        menuHeight,
        menuTop,
      },
    });
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    const {query} = this.state;
    // 开始抽奖
    if (nextProps.main.status.loadingGameLottery == false && this.props.main.status.loadingGameLottery == true) {
      let playthingVisible = nextProps.main.gameLotteries.length > 0 ? true : false;
      console.log(
        'index.tsx 游戏结束了呀',
        playthingVisible,
        'nextProps.main.gameLotteries',
        nextProps.main.gameLotteries,
      );
      this.handleGameInitAnimation('end', playthingVisible);
    }

    // 查询商品
    if (nextProps.main.status.loadingProduct == false && this.props.main.status.loadingProduct == true) {
      this.handleChangeOperate(nextProps.main.productItems);
    }

    // 做任务
    if (nextProps.main.status.computingTask == false && this.props.main.status.computingTask == true) {
      let success = nextProps.main.response.computedTask == CODE_SUCCESS ? true : false;

      // 如果是分享则不弹框提示
      console.log('index.tsx taskresponse', nextProps.main.taskType);
      if (nextProps.main.taskType == TASK_CONDITION_TYPE['game']) {
        Taro.showToast({
          title: success ? '任务完成' : '任务失败',
          icon: 'none',
        });
      }

      if (nextProps.main.response.computedTask == CODE_SUCCESS) {
        this.handleTaskSuccess();
      }
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // 抓取中
    if (prevState.catchingConfig.start == false && this.state.catchingConfig.start == true) {
      this.setState({
        gameOperates: this.state.currentOperates ? [CATCHING_OPERATES[1]] : [CATCHING_OPERATES[0]],
      });
    } else if (prevState.catchingConfig.start == true && this.state.catchingConfig.start == false) {
      this.handleChangeOperate(this.props.main.productItems);
    }

    // 判断动画下落
    if (
      this.state.catchingConfig.ropeAnimationCount == RETURN_ANIMATION &&
      prevState.catchingConfig.ropeAnimationCount !== this.state.catchingConfig.ropeAnimationCount
    ) {
      this.handlePlayGame(); // 调用游戏
    }
    // 判断动画上提，弹出结果框
    if (
      this.state.catchingConfig.ropeAnimationCount == OVER_ANIMATION &&
      prevState.catchingConfig.ropeAnimationCount !== this.state.catchingConfig.ropeAnimationCount
    ) {
      // 后台反馈成功则开始显示结果框
      const {query} = this.state;
      if (this.props.main.response.loadGameLottery == CODE_SUCCESS) {
        // 做任务的哦
        if (query && query.taskId && query.taskConditionsType) {
          if (query.taskConditionsType == TASK_CONDITION_TYPE['game']) {
            this.handleComputedTask(query);
          }
        }
        this.handleModalShowAndHide('result', true);
        this.handleClearAnimation('result');
        this.handleQueryGameInfo('player'); // 查询信息,带参数就不会去查许愿列表（模态框选中信息是靠gameinfo里的选中值来决定的）
        this.handleQueryUserInfo();
        this.handleQueryPropItems({pageNum: 0});
        this.handleQueryTaskItems({pageNum: 0});
      } else {
        this.handleClearAnimation();
      }
    }
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('catching handleGetRouterParams params', params);
    if (params.favorite || params.share) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }
    this.handleQuery();
    this.setState({
      query: params,
    });
  };

  /**
   * 查询信息
   */
  handleQuery = () => {
    this.handleQueryUserInfo(); // 查询用户信息
    this.handleQueryGameInfo(''); // 查询游戏信息
    this.handleQueryTaskItems({}); // 查询游戏任务列表
    this.handleQueryPropItems(); // 查询道具列表
  };

  /**
   * 做任务成功后的回调
   */
  handleTaskSuccess = () => {
    this.handleQueryUserInfo();
    this.handleQueryTaskItems({pageNum: 0}); // 查询游戏任务列表
    this.handleQueryPropItems({pageNum: 0});
  };

  /**
   * 查询道具
   */
  handleQueryPropItems = (pagation = {}) => {
    const {
      main: {
        prop: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadPropItems(params);
  };

  /**
   * 查询游戏信息
   */
  handleQueryGameInfo = (type) => {
    console.log('handleQueryhandleQueryGameInfo');
    let params = {};
    this.props.actions.action.loadGameInfo(params, type);
  };

  /**
   * 查询许愿商品信息
   */
  handleProductItems = () => {
    const {
      main: {gameInfo},
    } = this.props;
    let params = {
      prizeConfigId: gameInfo.prizeConfigVO.id,
    };
    if (params.prizeConfigId) {
      this.props.actions.action.loadProductItems(params);
    }
  };

  /**
   * 查询会员信息
   */
  handleQueryUserInfo = () => {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  };

  /**
   * 查询游戏任务列表
   */
  handleQueryTaskItems = (pagation) => {
    // 编辑参数
    const {
      main: {
        task: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadTaskItems(params);
  };

  /**
   * 操作处理（单次or多次）
   */
  handleOperate = (data, operateIndex) => {
    console.log('index.tsx handleOperate data', data);

    const {
      main: {userInfo, gameInfo, currentWish, productItems},
    } = this.props;

    console.log('index.tsx handleOperate gameInfo=', gameInfo);

    // 判断是否能玩
    if (!gameInfo.isPlay) {
      // 判断游戏时间是否再范围内
      const currentTime = moment();
      let gameStartTime = moment(gameInfo.gameStartTime);
      let gameEndTime = moment(gameInfo.gameEndTime);

      if (gameEndTime && gameEndTime) {
        if (!(currentTime.isBefore(gameEndTime) && currentTime.isAfter(gameStartTime))) {
          this.handleMessageShowAndHide('游戏暂无开启,敬请期待', true, 3000);
          return;
        }
      } else if (!gameStartTime && !gameEndTime) {
        this.handleMessageShowAndHide('游戏暂无开启,敬请期待', true, 3000);
        return;
      }
      // 许愿池没有商品
      else {
        this.handleMessageShowAndHide('许愿池努力填满中,敬请期待', true, 3000);
        return;
      }
    }

    if (currentWish && currentWish.id) {
      // 判断是否是会员
      if (!userInfo.accountType) {
        // 弹框显示非会员
        this.handleModalShowAndHide('member', true);
        return;
      }

      // 判断魔力币是否足够
      if (userInfo.magicCoin < data.score) {
        this.handleMessageShowAndHide('魔力币不足，请充值', true, 3000);
        return;
      }
      // 判断是否有次数玩 （单抽判断）
      if (gameInfo.playTimes != null) {
        if (!gameInfo.playTimes) {
          this.handleMessageShowAndHide('今日游戏次数已达上限', true, 3000);
          return;
        }

        // 多抽
        if (data.count == 10 && gameInfo.playTimes < 10) {
          this.handleMessageShowAndHide('今日游戏次数已不足10次~', true, 3000);
          return;
        }
      }

      // 更新开始抓取
      this.setState({
        catchingConfig: {
          ...this.state.catchingConfig,
          start: true,
          type: data.type,
        },
        currentOperates: operateIndex,
        ropeSettings: {
          ...this.state.ropeSettings,
          reset: false,
        },
      });

      this.handleGameInitAnimation('start', false); //  抓取动画开始
    } else {
      this.handleMessageShowAndHide('请先选择心愿哦~', true, 3000);
    }
  };

  /**
   * 开始玩游戏
   */
  handlePlayGame = () => {
    const {
      main: {gameInfo, currentWish},
    } = this.props;
    const {wishOperates, currentOperates, selectedProp} = this.state;
    console.log('catchplaything handlePlayGame selectedProp=', selectedProp);

    console.log('catchPlaything handlePlayGame gameInfo', gameInfo);
    let operateCurrent = wishOperates.find((i, index) => index == currentOperates);
    if (operateCurrent && operateCurrent.count) {
      if (currentWish && currentWish.id) {
        // 编辑参数
        let params = {
          customerWishId: currentWish.id,
          ipId: gameInfo.ipId,
          magicCoin: operateCurrent.score,
          playTimes: operateCurrent.count,
          prizeConfigId: gameInfo.prizeConfigId,
        };

        // 判断是否使用道具
        if (selectedProp && selectedProp.propId) {
          params.propId = selectedProp.propId;
          params.myPropId = selectedProp.id;
        }
        console.log('index.tsx handlePlayGame params=', params);

        this.props.actions.action.gameLottery(params);
      }
    } else {
      this.handleMessageShowAndHide('游戏配置缺失，无法开启游戏', true, 3000);
    }
  };

  /**
   * 游戏动画
   */
  handleGameInitAnimation = (type, data) => {
    console.log('index.tsx handleGameInitAnimation type', type, 'data', data);
    // 绳子右移下降
    this.handleCreateGameRopeAnimation(type);

    // 球动画效果
    this.handleCreateGamePlaythingAnimation(type, data);
  };

  /**
   * 绳子动态效果
   */
  handleCreateGameRopeAnimation = (type) => {
    const {
      ropeAnimation: {createAnimation, config},
    } = this.state;
    let animation = createAnimation;

    // 开始
    if (type == 'start') {
      animation.translate('100px', 0).step({
        ...config,
      });
      animation.translate('100px', '100px').step({
        ...config,
      });
    }

    // 结束
    else {
      animation.translate('100px', 0).step({
        ...config,
        delay: 900,
      });
    }

    this.setState({
      ropeAnimation: {
        ...this.state.ropeAnimation,
        animation: animation.export(),
      },
    });
  };

  /**
   * 球的动态效果
   */
  handleCreateGamePlaythingAnimation = (type, visible) => {
    console.log('handleCreateGamePlaytingAnimation visible', visible, 'type', type);
    const {
      playthingAnimation: {createAnimation, config},
    } = this.state;

    let animation = createAnimation;

    // 结束
    if (type == 'end') {
      // 后台有礼物返回，并且下落动画播放完毕后
      if (visible) {
        animation.opacity(1).step({
          ...config,
          delay: 0,
        });
      }
      animation.translate('100px', '-10px').step({
        ...config,
        delay: 0,
      });
    }

    // 开始
    else {
      animation.translate('100px', 0).step({
        ...config,
      });
      animation.translate('100px', '90px').step({
        ...config,
      });
    }
    this.setState({
      playthingAnimation: {
        ...this.state.playthingAnimation,
        animation: animation.export(),
      },
    });
  };

  /**
   * 绳子动画结束 （下落去调用后台接口返回是否能抓到娃娃）
   * @param e
   */
  handleRopeTransitonEnd = (e) => {
    const {
      catchingConfig: {ropeAnimationCount},
    } = this.state;

    this.setState({
      catchingConfig: {
        ...this.state.catchingConfig,
        ropeAnimationCount: ropeAnimationCount + 1,
      },
    });
  };

  /**
   * 渲染页面
   * @returns
   */
  render() {
    if (!this.props.main) return null;

    let {
      main: {isLoading},
    } = this.props;
    const {
      gameOperates,
      navbarSettings: {navBarHeight},
    } = this.state;
    console.log(isLoading);

    return (
      <View className="pageCatchPlaythingPa" catchMove>
        {this.renderNavBar()}
        <ScrollView scrollY className="catchPlaythingScrollview">
          <View className="scrollViewC">
            {this.renderStarBj()}
            {this.renderLuckyProcessContent()}
            <View className="extraMessage">
              {this.renderMessageContent()}
              {this.renderStrategyContent()}
            </View>
            <View className="dollMachine">
              {this.renderDollMachineTitleContent()}
              {this.renderDollMachineAnimationContent()}
              {this.renderDollDiver()}
              {this.renderOperatesContent(gameOperates)}
              {this.renderOutIcon()}
              {this.renderInsertContent()}
              {this.renderGameExtraMessage()}
            </View>
            {this.renderPrizeResultModal()}
            {this.renderMemberModal()}
            {this.renderTaskModal()}
            {this.renderStrategyModal()}
            {this.renderNextModal()}
            {this.renderWishModal()}
            {this.renderPropModal()}
            {this.renderAdvModal()}
          </View>
        </ScrollView>
      </View>
    );
  }

  /**
   * 渲染基本信息
   */
  renderNavBar() {
    const {
      navbarSettings: {navBarHeight, menuHeight, menuTop},
      catchingConfig: {start},
    } = this.state;

    console.log('catchplaything renderNavBar navBarHeight=', navBarHeight);
    return (
      <View className="navHeader" style={{height: navBarHeight}}>
        <View className="navbar" style={{height: navBarHeight}}>
          <View style={{height: menuHeight, top: menuTop}} className="navBarContent">
            {!start && <View className="at-icon at-icon-chevron-left" onClick={this.handleNavBack}></View>}
            <View className="navTitle">{NAVBAR_TITLE}</View>
          </View>
        </View>
      </View>
    );
  }

  /**
   * 点击返回
   */
  handleNavBack = () => {
    Taro.navigateBack();
  };

  /**
   * 渲染星背景
   * @returns
   */
  renderStarBj() {
    return <View className="starBj"></View>;
  }

  /**
   * 渲染幸运值进度条
   * @returns
   */
  renderLuckyProcessContent() {
    let {
      main: {
        gameInfo: {luckyValue},
      },
    } = this.props;
    console.log('index.tsx luckyValue', luckyValue);
    luckyValue = luckyValue || 0;
    return (
      <View className="progress">
        <View className="progress-bar" style={{width: luckyValue + '%'}}></View>
        <View className="progress-title">幸运值&nbsp;{luckyValue + '%'}</View>
      </View>
    );
  }

  /**
   * 渲染欧气攻略
   */
  renderStrategyContent() {
    return (
      <View className="strategy" onClick={this.handleStrategy}>
        <View className="strategyLabel">欧气攻略</View>
      </View>
    );
  }

  /**
   * 点击欧气攻略
   */
  handleStrategy = () => {
    this.handleModalShowAndHide('strategy', true);
  };

  /**
   * 渲染气泡信息
   */
  renderMessageContent() {
    const {
      message: {title, visible},
    } = this.state;

    return (
      <View style={{visibility: visible ? 'visible' : 'hidden'}}>
        <View className="message">
          <View className="title">{title}</View>
        </View>
      </View>
    );
  }

  /**
   * 渲染信息弹出和隐藏
   */
  handleMessageShowAndHide(title, visible, duration) {
    this.setState({
      message: {
        title: visible ? title : '',
        visible: visible,
      },
    });

    // 持续时间
    if (duration) {
      setTimeout(() => {
        this.setState({
          message: {
            title: '',
            visible: false,
          },
        });
      }, duration);
    }
  }

  /**
   * 渲染抓娃娃机头部
   * @returns
   */
  renderDollMachineTitleContent() {
    const {pics} = this.state;
    return (
      <View
        className="header"
        style={{
          background: `url('${BACKAGROUND_IMAGE_BASE64['headerBj']}') no-repeat`,
          backgroundSize: '100% 100%',
        }}
      >
        <Image src={pics.headerTitle} className="titleImage" />
      </View>
    );
  }

  /**
   * 渲染娃娃机中部动画部分内容
   */
  renderDollMachineAnimationContent() {
    const {pics, ropeAnimation, playthingAnimation} = this.state;
    const {
      main: {gameInfo, currentWish},
    } = this.props;
    console.log('index.tsx renderDollMachineAnimationContent gameInfo', gameInfo);

    return (
      <View
        className="middle"
        style={{
          background: `url('${BACKAGROUND_IMAGE_BASE64['contentBj']}') no-repeat`,
          backgroundSize: '100% 100%',
        }}
      >
        <View className="wish">
          <Image src={pics.wish} onClick={this.handleWish} className="wishIcon" />
          <View className="wishLabel">{currentWish && currentWish.id ? '已许愿' : '许愿'}</View>
        </View>
        <View className="gift">
          <Image src={pics.gift} onClick={this.handleTask} className="giftIcon" />
          <View className="giftLabel">领福利</View>
        </View>
        <View className="prop">
          <Image src={pics.propBuffIcon} onClick={this.handleProp} className="propIcon" />
          <View className="propLabel">魔力进阶 </View>
        </View>
        <View className="next" style={{display: gameInfo && gameInfo.isAdvance ? 'block' : 'none'}}>
          <Image src={pics.ChessPreview} onClick={this.handleNextPreview} className="nextIcon" />
          <View className="nextLabel">下期预告 </View>
        </View>
        <View className="content">
          <View
            className="bj"
            style={{
              background: `url('${BACKAGROUND_IMAGE_BASE64['purpleBj']}') no-repeat`,
              backgroundSize: '100% 100%',
            }}
          >
            <View
              className="catchIcon"
              animation={ropeAnimation.animation}
              onTransitionEnd={this.handleRopeTransitonEnd}
            ></View>
            <View className="singlePlaything" animation={playthingAnimation.animation}></View>
            <View
              className="playthings"
              style={{
                background: `url('${BACKAGROUND_IMAGE_BASE64['playthings']}') no-repeat`,
                backgroundSize: '100% 100%',
              }}
            ></View>
          </View>
        </View>
      </View>
    );
  }

  /**
   * 灰色间隔
   */
  renderDollDiver() {
    return (
      <View
        className="dollDiver"
        style={{
          background: `url('${BACKAGROUND_IMAGE_BASE64['catchingDiver']}') no-repeat`,
          backgroundSize: '100% 100%',
        }}
      ></View>
    );
  }

  /**
   * 魔力进阶
   */
  handleProp = () => {
    const {selectedProp} = this.state;
    console.log('catchplaything handleProp selectedProp', selectedProp);
    this.handleModalShowAndHide('propEffect', true);
  };

  /**
   * 分享
   */
  handleShare = () => {
    console.log('index.tsx handleShare');
  };

  /**
   * 许愿
   */
  handleWish = () => {
    this.handleModalShowAndHide('wish', true);
  };

  /**
   * 领福利任务
   */
  handleTask = () => {
    const {
      main: {userInfo},
    } = this.props;
    // 非会员不能做任务，让他开会员
    if (!userInfo.accountType) {
      this.handleModalShowAndHide('member', true);
    } else {
      this.handleModalShowAndHide('task', true);
    }
  };

  /**
   * 下期预告
   */
  handleNextPreview = () => {
    console.log('index.tsx handleNextPreview');
    this.handleModalShowAndHide('next', true);
  };

  /**
   * 渲染操作内容
   */
  renderOperatesContent(OPEARTES) {
    const {
      catchingConfig: {start},
    } = this.state;

    return (
      <View
        className="footer"
        style={{
          background: `url('${BACKAGROUND_IMAGE_BASE64['operateBj']}') no-repeat`,
          backgroundSize: '100% 100%',
        }}
      >
        {OPEARTES.map((i: any, index: number) => (
          <Button
            className={OPEARTES.length == 2 ? (index == 0 ? 'singleOperate' : 'moreOperate') : i.className}
            key={index}
            onClick={() => this.handleOperate(i, index)}
            disabled={start}
          >
            <Text className="label">{i.name}</Text>
          </Button>
        ))}
      </View>
    );
  }

  /**
   * 底部魔力币显示
   * @returns
   */
  renderInsertContent() {
    const {pics} = this.state;
    const {
      main: {userInfo},
    } = this.props;

    console.log('index.tsx userInfo', userInfo);

    return (
      <View
        className="insert"
        style={{
          background: `url('${BACKAGROUND_IMAGE_BASE64['insertBj']}') no-repeat`,
          backgroundSize: '100% 100%',
        }}
      >
        <View className="info">
          <Image src={pics.coin} className="coin" />
          <Text className="label">魔力币:{userInfo.magicCoin}</Text>
          <Image
            src={pics.topUp}
            className="topUpIcon"
            onClick={this.handleRecharge}
            style={{display: userInfo.accountType ? 'inline-block' : 'none'}}
          />
        </View>
      </View>
    );
  }

  /**
   * 渲染口袋样式
   */
  renderOutIcon() {
    const {pics} = this.state;
    return <Image src={pics.outIcon} className="outIcon" />;
  }

  /**
   * 充值
   */
  handleRecharge = () => {
    const {
      catchingConfig: {start},
    } = this.state;
    if (start) {
      return;
    }

    Taro.navigateTo({
      url: '/pages/package-I/syntheticRecharge/index',
    });
  };

  /**
   * 结果模态框
   */
  renderPrizeResultModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <ResultModal
        navbarSettings={navbarSettings}
        onPlayAgain={this.handlePlayAgin}
        visible={visible && type == 'result'}
        onCancel={this.handleCancelResult}
      />
    );
  }

  /**
   * 再来一次
   */
  handlePlayAgin = () => {
    this.handleClearAnimation();
    this.handleModalShowAndHide('', false);
  };

  /**
   * 关闭模态框内容充值
   */
  handleCancelResult = () => {
    this.handleClearAnimation();
    this.handleModalShowAndHide('', false);
  };

  /**
   * 模态框的弹出和隐藏
   */
  handleModalShowAndHide = (type, visible, item = null) => {
    console.log('index.tsx handleModalShowAndHide type', type, 'visible', visible);

    const {
      catchingConfig: {start},
    } = this.state;

    // 游戏中不能打开任何弹框
    if (visible && start && type != 'result') {
      return;
    }
    console.log('点击操作哦 start', start);

    this.setState({
      modal: {
        ...this.state.modal,
        type: visible ? type : '',
        visible,
        item,
      },
    });
  };

  /**
   * 位置归置0 （实验中）
   */
  handleClearAnimation = (type = '') => {
    console.log('index.tsx handleClearAnimation type=', type);
    // 抓取状态更新
    this.setState({
      catchingConfig: {
        start: false,
        type: '',
        ropeAnimationCount: 0,
      },
      currentOperates: -1,
      ropeSettings: {
        ...this.state.ropeSettings,
        reset: true,
      },
      query: type
        ? {...this.state.query}
        : {
            ...this.state.query,
            taskId: '', // 任务id
            taskConditionsType: '', // 任务类型
          },
      selectedProp: null, // 选择道具
    });

    let ropeA = Taro.createAnimation({
      duration: 0,
      timingFunction: 'linear',
    });
    let ropeAnimationClear = ropeA;
    ropeAnimationClear.step({duration: 0});

    let playthingA = Taro.createAnimation({
      duration: 0,
      timingFunction: 'linear',
    });
    let playthingAnimationClear = playthingA;
    playthingAnimationClear.opacity(0).step({duration: 100});
    playthingAnimationClear.step({duration: 0});

    this.setState({
      ropeAnimation: {
        ...this.state.ropeAnimation,
        createAnimation: ropeA,
        animation: ropeAnimationClear.export(),
      },
      playthingAnimation: {
        ...this.state.playthingAnimation,
        createAnimation: playthingA,
        animation: playthingAnimationClear.export(),
      },
    });
  };

  /**
   * 渲染新人生效中 (玩的过程再显示)
   * @returns
   */
  renderGameExtraMessage() {
    const {
      userInfo: {isNewComer},
    } = this.props.main;
    const {catchingConfig} = this.state;
    return catchingConfig.start && isNewComer ? <View className="gameExtraMessage">新人加成生效中</View> : <></>;
  }

  /**
   * 渲染会员弹框
   */
  renderMemberModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <MemberModal
        navbarSettings={navbarSettings}
        visible={visible && type == 'member'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onActivate={() => this.handleActivateMember()}
      />
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.handleModalShowAndHide('', false); // 关闭模态框
    // 跳转到开通会员界面
    Taro.navigateTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 渲染魔力币获取模态框游戏任务
   */
  renderTaskModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <TaskModal
        visible={visible && type == 'task'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onQueryTask={this.handleQueryTaskItems}
        navbarSettings={navbarSettings}
      />
    );
  }

  /**
   * 渲染攻略弹框
   */
  renderStrategyModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <StrategyModal
        visible={visible && type == 'strategy'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        navbarSettings={navbarSettings}
      />
    );
  }

  /**
   * 渲染下期公告
   * @returns
   */
  renderNextModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <NextItemModal
        visible={visible && type == 'next'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        navbarSettings={navbarSettings}
      />
    );
  }

  /**
   * 渲染许愿模态框
   */
  renderWishModal() {
    const {
      modal: {visible, type, item},
      navbarSettings,
    } = this.state;

    return (
      <WishModal
        visible={visible && type == 'wish'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onQueryGame={this.handleQueryGameInfo}
        navbarSettings={navbarSettings}
      />
    );
  }

  /**
   * 选择商品后更新操作列表
   */
  handleChangeOperate = (data) => {
    console.log('handleChangeOpreate data', data);

    const {
      main: {currentWish, productItems},
    } = this.props;
    const {
      catchingConfig: {start},
    } = this.state;

    if (start) {
      return;
    }

    let currentItem = data.find((i) => i.goodsInfoId == currentWish.goodsInfoId);
    console.log(
      'index.tsx handleChangeOperate currentWish',
      currentWish,
      'currentItem',
      currentItem,
      'productItems',
      productItems,
    );

    let operates = [];

    // 有值取选择的商品的配置值
    if (currentWish && currentWish.id && currentItem) {
      operates = [
        {
          name: `${currentItem.singlePrice}币/次`,
          className: 'singleOperate',
          score: currentItem.singlePrice,
          count: 1,
        },
        {
          name: `${currentItem.tenTimesPrice}币/十次`,
          className: 'moreOperate',
          score: currentItem.tenTimesPrice,
          count: 10,
        },
      ];
    } else {
      console.log('index.tsx 取消');
      operates = DEFALUT_OPERATES;
    }

    this.setState({
      gameOperates: operates,
      wishOperates: operates,
    });
  };

  /**
   * 渲染道具模态框
   */
  renderPropModal() {
    const {
      modal: {visible, type, item},
      selectedProp,
      navbarSettings,
    } = this.state;
    console.log('catchPlaything renderPropModal selectProp', selectedProp);

    return (
      <PropModal
        selectItem={selectedProp}
        visible={type == 'propEffect'}
        onCancel={(type) => this.handleCancelSelectProp(type)}
        onUse={this.handleUseSelectProp}
        onQueryProp={this.handleQueryPropItems}
        navbarSettings={navbarSettings}
      />
    );
  }

  /**
   * 取消道具使用
   */
  handleCancelSelectProp = (type) => {
    // 取消选中就不关
    if (type != 'selectedCancel') {
      this.handleModalShowAndHide('', false); // 关闭模态框
    } else {
      this.setState({
        selectedProp: null,
      });
    }
  };

  /**
   * 选择道具
   */
  handleUseSelectProp = (data) => {
    this.setState({
      selectedProp: data,
    });
    this.handleModalShowAndHide('', false); // 关闭模态框
  };

  /**
   * 渲染广告模态框
   */
  renderAdvModal() {
    const {
      adModal: {imgUrl, isModalFlag, jumpPage},
      navbarSettings,
    } = this.state;
    return (
      <AdvModal
        navbarSettings={navbarSettings}
        imgUrl={imgUrl}
        handleUrl={() => handleUrl(jumpPage)}
        handleClose={() => this.handleCloseAtModal()}
        isModalFlag={isModalFlag}
      />
    );
  }

  /**
   * 关闭广告模态框
   */
  handleCloseAtModal = () => {
    const {adModal} = this.state;

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: false,
        },
      },
      async () => {
        if (this.state.adModal.nextPopupId) {
          await this.handleAdModalUpdateStatus(this.state.adModal.nextPopupId);
        }
      },
    );
  };

  /**
   * 广告弹出
   * @param id
   */
  async handleAdModalUpdateStatus(id) {
    const {adModal} = this.state;
    const res = await fetchModal(adModal.type);
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, adModal.type, popupId);

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: flagParams.showFlag,
          imgUrl: flagParams.imgUrl,
          jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
          nextPopupId: flagParams.nextPopupId,
        },
      },
      () => {
        if (this.state.adModal.nextPopupId && !this.state.adModal.isModalFlag) {
          this.isGo(this.state.adModal.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.handleAdModalUpdateStatus(id);
  }

  /**
   * 分享好友
   * @param res
   * @returns
   */
  onShareAppMessage(res) {
    const {
      pics: {gameShareThum},
      query,
    } = this.state;

    console.log('index.tsx onshareAPPmESSAGE query=', query);

    if (query && query.taskConditionsType == TASK_CONDITION_TYPE['share']) {
      this.handleComputedTask(query);
    }
    return {
      title: GAME_SHARE_TITLE,
      path: '/pages/package-I/home/index',
      imageUrl: gameShareThum,
      query: 'share=true',
    };
  }

  /**
   * 完成任务
   */
  handleComputedTask = (data) => {
    this.setState({
      query: {
        ...this.state.query,
        taskConditionsType: '',
        taskId: '',
      },
    });

    // 编辑参数
    let params = {
      id: data.taskId,
      taskConditionsType: data.taskConditionsType,
    };
    console.log('catchplaything handleComputedTask data', data, 'query', this.state.query);
    this.props.actions.action.computedTask(params);
  };

  /**
   * 分享到朋友圈
   * @param res
   * @returns
   */
  onShareTimeline(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      path: '/pages/package-I/home/index',
      query: 'share=true',
    };
  }

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
